package com.damai.pay.wx;

import java.io.IOException;
import java.text.ParseException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.citywithincity.api.ApiConfig;
import com.citywithincity.pay.PayException;
import com.citywithincity.pay.PayType;
import com.citywithincity.utils.DateTimeUtil;
import com.damai.error.SignException;
import com.damai.pay.PayAdapter;
import com.damai.pay.PayAdapterListener;
import com.damai.pay.PayAdapterManager;
import com.damai.pay.PayBusinessException;
import com.damai.pay.PayInfo;

public class WXPayAdapter implements PayAdapter<WXOrder> {

	protected WXPayModel wxPayModel;
	private PayAdapterListener listener;
	private String key;
	
	public WXPayAdapter(WXConfig config,
			PayAdapterListener listener,
			String key){
		this.wxPayModel = new WXPayModel(config.getAppId(), config.getWxKey(), config.getMchId());
		this.listener = listener;
		this.key =key;
		PayAdapterManager.register(key, this);
	}
	
	

	private static final String SUCCESS = "success";
	private static final String FAIL = "fail";

	@Override
	public void onServerNotify(HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, String> map = wxPayModel.parseOrder(request);
			//解析出来的，那么就去业务逻辑层面
			String time = map.get("time_end");
			
			try {
				onPaySuccess(map.get(WXPayModel.out_trade_no),map.get(WXPayModel.transaction_id),DateTimeUtil.parseShortDateTime(time));
			} catch (ParseException e) {
				
			}
			renderOk(response);
		} catch (IOException e) {
			//xml解析失败
			renderOk(response);
		} catch (SignException e) {
			//签名错误,不做处理，本订单无效
			renderOk(response);
		} catch (PayBusinessException e) {
			renderError(response);
		}
	}
	
	private void renderOk(HttpServletResponse response){
		try {
			response.getWriter().print(SUCCESS);
		} catch (IOException e) {
			
		}
	}

	/**
	 * 支付成功
	 * @param outId
	 * @param platId
	 * @throws PayBusinessException
	 */
	protected void onPaySuccess(String outId, String platId,java.util.Date date) throws PayBusinessException{
		listener.onPaySuccess(PayType.PayType_WX, outId, platId, date,null);
	}

	private void renderError(HttpServletResponse response) {
		try {
			response.getWriter().print(FAIL);
		} catch (IOException e) {
			
		}
	}



	@Override
	public Object prePay(WXOrder order, HttpServletRequest request) throws PayException, IOException {
		int fee = order.getFee();
		Object info = wxPayModel.prePay(order.getOutId(), 
				order.getTitle(),  ApiConfig.debug() ? 1 : fee,
				getNotifyUrl(), 
				request.getRemoteAddr());
		
		return info;
	}

	private String getNotifyUrl() {
		return PayAdapterManager.getNotifyUrl(key);
	}

	@Override
	public void refund(WXOrder order) throws PayException, IOException {
		String outId = order.getOutId();
		wxPayModel.refund(outId, outId, order.getFee());
	}

	@Override
	public PayInfo getPayInfo(WXOrder order,Map<String, Object> json) throws PayException, IOException {
		Map<String, String> map = wxPayModel.queryOrder(order.getOutId());
		PayInfo info = new WXPayInfo(map);
		return info;
	}

}
